import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import TableDefined from '@/components/common/tableDefined'
import './index.less'
import { Button, Input, Select, Modal, DatePicker, Form, Row, Col, TimePicker, Steps, Table, Checkbox,message } from 'antd';
import Dynamic from '@/api/dynamic'
import DefineSelect from '@/components/common/tableDefinedEdit/DefineSelect.tsx'
const { Option } = Select;

const CleanRole: FC = () => {
  const tableRef: RefType = useRef()
  const AddMComRef: RefType = useRef()
  const LogMComRef: RefType = useRef()
  const [searchConfigList, setsearchConfigList] = useState([]);
  const [orderBy, setOrderBy] = useState('');
  const [loading, setLoading] = useState(true);
  const [connector, setconnector] = useState({});
  useEffect(() => {
    getSearchConfig();
  }, [])

  const getSearchConfig = () => {
    Dynamic.getDynamicQuery({
      apiID: 'DMT_MNG_01',
      apiParam: {
        api_id: 'DMT_B001'
      }
    }).then((res) => {
      let data = res.data;
      let apiParamStr = data.data['0']['api_param'] ? data.data['0']['api_param'] : '';
      let apiParam = data.data['0']['api_param'] ? JSON.parse(data.data['0']['api_param']) : {};
      let { paramList = [] } = apiParam;
      paramList.map((e, i) => {

        switch (e.name) {
          case "where"://查询条件
            let element = e.element || [];
            let searchConfigListNew = [];

            let connectorNew = {};

            element.map((el, il) => {
              connectorNew[el.feild] = el['connector'];
              let ele = {
                "key": el.feild,
                // "slot": <Input placeholder={"请输入"+el.label} allowClear />,
                "rules": [],
                // "initialValue": '',
                "label": el.label,
              }
              switch (el.type) {
                case 'text':
                  ele['slot'] = <Input placeholder={"请输入" + el.label} allowClear />;
                  break;
                case 'checkbox':
                  ele['slot'] = <Checkbox.Group style={{ maxWidth: window.innerWidth / 2 - 100 + 'px' }}>
                    {
                      el.option.map((ek, ik) => {
                        return <Checkbox defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Checkbox>
                      })
                    }
                  </Checkbox.Group>
                  break;
                case 'select':
                  if (el?.option_url) {
                    if (el.mode == "multiple") {
                      ele['slot'] = <DefineSelect mode='multiple' {...el.option_url} />
                      ele['initialValue'] = [];
                    } else {
                      ele['slot'] = <DefineSelect {...el.option_url} />
                    }

                  } else {
                    if (el.mode == "multiple") {
                      ele['slot'] = <Select allowClear mode='multiple' placeholder={'请选择' + el.label} style={{ maxWidth: window.innerWidth / 2 - 100 + 'px', minWidth: '120px' }}>
                        {
                          el.option.map((ek, ik) => {
                            return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                          })
                        }
                      </Select>
                    } else {
                      ele['slot'] = <Select allowClear placeholder={'请选择' + el.label} style={{ maxWidth: window.innerWidth / 2 - 100 + 'px', minWidth: '120px' }}>
                        {
                          el.option.map((ek, ik) => {
                            return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                          })
                        }
                      </Select>
                    }
                  }


                default:
                  break;
              }
              searchConfigListNew.push(ele)
              setconnector(connectorNew)
            })
            setsearchConfigList(searchConfigListNew);

            break;
          case 'orderBy'://排序
            setOrderBy(e.value);
            break;
          case 'paging'://分页
            break;
        }
      })

      setLoading(false);
    })

  }
  // const searchConfigList = [
  //   {
  //     key: 'et.task_name',
  //     slot: <Input placeholder="请输入关键字" allowClear />,
  //     rules: [],
  //     initialValue: ''
  //   }
  // ];
  const columns = [
    // {
    //   title: '序号',
    //   align: 'center',
    //   dataIndex: 'index',
    //   key: 'index',
    //   width: '80px',
    //   fixed: 'left',
    //   render: (text, record, index) => {
    //     return index + 1
    //   }
    // },
    // {
    //   title: '规则名称',
    //   dataIndex: 'task_name',
    //   key: 'task_name',
    // },
    // {
    //   title: '调度规则',
    //   dataIndex: 'sch_type',
    //   key: 'sch_type',
    //   render(txt){
    //     return schTypeObj[txt];
    //   },
    // },
    // {
    //   title: '目标数据源',
    //   dataIndex: 'db_source',
    //   key: 'db_source',
    // },
    // {
    //   title: '脚本类型',
    //   dataIndex: 'script_type',
    //   key: 'script_type',
    //   render(txt){
    //     return scripTypeObj[txt];
    //   },
    // },
    // {
    //   title: '更新时间',
    //   dataIndex: 'update_time',
    //   key: 'update_time',
    //   render(txt) {
    //     return moment(txt).format('YYYY-MM-DD HH:mm:ss')
    //   },
    // },
    {
      title: '操作',
      dataIndex: 'scan',
      key: 'scan',
      width: '270px',
      fixed: 'right',
      render(txt, record, index) {
        return <div>
          <Button className="btn" onClick={() => show(record.sch_id)} size="small">
            查看
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => start(record.sch_id)} size="small">
            启动
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => stop(record.sch_id)} size="small">
            停止
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => del(record.sch_id)} size="small">
            删除
          </Button>
        </div>
      }
    },
  ]
  const show = (id) => {
    console.log(id);
    AddMComRef.current.init(id);
  }
  const start = (id) => {
    console.log(id);
    Dynamic.DynamicExecute({
      apiID: 'DMT_B001_01',
      apiParam: {
        sch_id: id
      }
    }).then((res) => {
      message.success('启动成功')
      tableRef.current.update();
    })
  }
  const stop = (id) => {
    console.log(id);
    Dynamic.DynamicExecute({
      apiID: 'DMT_B001_02',
      apiParam: {
        sch_id: id
      }
    }).then((res) => {
      message.success('停止成功')
      tableRef.current.update();
    })
  }
  const del = (id) => {
    console.log(id);
    Modal.confirm({
      title: '确认删除？',

      onOk() {
        // Role.roleDel({
        //   roleid:record.roleid,
        //   isFormData:true
        // }).then(()=>{
        //   tableRef.current.update();
        // })
        Dynamic.DynamicExecute({
          apiID: 'DMT_B001_03',
          apiParam: {
            sch_id: id
          }
        }).then((res) => {
          message.success('删除成功')
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  return (
    <>
      {
        !loading && <TableDefined
          apiFun={Dynamic.getDynamicQuery}
          columns={columns}
          ref={tableRef}
          searchConfigList={searchConfigList}
          extraProps={{ apiID: 'DMT_B001', apiParam: { 'orderBy': orderBy } }}
          // onSelectRow={(val) => {
          //   console.log(val);
          // }}
          rowKey='id'
          beforeSearch={(val: any) => {
            // eslint-disable-next-line no-param-reassign
            console.log(val);
            val.where = [];
            for (let i in val) {
              if (i != 'where' && val[i] && val[i]['length'] > 0) {
                val.where.push({ "feild": i, "connector": connector[i], "value": val[i] })
              }
            }
            for (let i in val) {
              if (i != 'where') {
                delete val[i];
              }
            }
            // eslint-disable-next-line no-param-reassign
            return {}
          }}
        />
      }
      <AddMCom ref={AddMComRef} callback={() => {
        tableRef.current.update();
      }} />

      

    </>
  )
}
export default withRouter(CleanRole)


const AddM = (props, refs) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [id, setid] = useState('');
  const [logVisible, setlogVisible] = useState(false);
  const [log, setlog] = useState('');
  // const [isLoading,setisLoading ] = useState(false);
  const showModal = () => {
    setIsModalVisible(true);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    props.callback && props.callback();
  };
  useImperativeHandle(refs, () => ({
    init: (id) => {
      console.log('123');
      setid(id)
      // setfileList([]);
      showModal();
      // getDetail();
    }
  }))
  // const getDetail  = ()=>{
  //   Dynamic.getDynamicQuery({
  //     apiID:'DMT_B002_01',
  //     apiParam:{
  //       sch_id:'sch_id'
  //     }
  //   }).then((res)=>{
  //     console.log(res);
  //   })
  // }

  const columns = [
    {
      title: '操作',
      dataIndex: 'scan',
      key: 'scan',
      width: '120px',
      fixed: 'right',
      render(txt, record, index) {
        return <div>
          <Button className="btn" onClick={() => {
            setlogVisible(true);
            let html = record.run_log.replaceAll('\n', '<br />')
            setlog(html)
          }} size="small">
            详情
          </Button>
        </div>
      }
    },
  ]
  return <Modal
    title={'日志'}
    visible={isModalVisible}
    onCancel={handleCancel}
    centered={true}
    width={1200}
    destroyOnClose={true}
    maskClosable={false}
    className="dataTemModal"
    footer={
      <Button onClick={handleCancel}>关闭</Button>
    }
  >
    {
      isModalVisible && <TableDefined
        apiFun={Dynamic.getDynamicQuery}
        columns={columns}
        hiddenRefs={true}
        // ref={tableRef}
        extraProps={{
          apiID: 'DMT_B002_01', apiParam: {
            where: [{ feild: "sch_id", connector: "eq", value: id }],
            orderBy: "start_time desc"
          }
        }}
        scrollOption={{ y: 300 }}
        // onSelectRow={(val) => {
        //   console.log(val);
        // }}
        rowKey='id'
      />
    }

    <Modal
      title={'日志'}
      visible={logVisible}
      onCancel={() => setlogVisible(false)}
      centered={true}
      width={580}
      destroyOnClose={true}
      maskClosable={false}
      className="dataTemModal"
      bodyStyle={{
        maxHeight: window.innerHeight - 160,
        overflow: "auto"
      }}
      footer={
        <Button onClick={() => setlogVisible(false)}>关闭</Button>
      }
    >
      <div>
        {
          log.split('<br />').map((e, i) => {
            return <div key={i}>{e}</div>
          })
        }
      </div>
      {/* {log} */}
    </Modal>
  </Modal>
}

const AddMCom = forwardRef(AddM);



